package com.i360day.invoker;

import com.i360day.invoker.common.HttpInvokerRemoteConstant;
import com.i360day.invoker.http.Request;
import com.i360day.invoker.http.Response;
import com.i360day.invoker.properties.HttpInvokerProperties;
import com.i360day.invoker.request.HttpInvokerRequest;
import com.i360day.invoker.socket.SimpleWebSocketTemplate;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;

/**
 * 获取到上下文socket manage
 */
public class WebSocketHttpInvokerRequest implements HttpInvokerRequest {

    private SimpleWebSocketTemplate webSocketTemplate;
    private HttpInvokerProperties httpInvokerProperties;

    public WebSocketHttpInvokerRequest(SimpleWebSocketTemplate webSocketTemplate, HttpInvokerProperties httpInvokerProperties) {
        this.webSocketTemplate = webSocketTemplate;
        this.httpInvokerProperties = httpInvokerProperties;
    }

    @Override
    public Response executor(RequestTemplate requestTemplate) throws IOException {

        Request request = requestTemplate.convertRequest();

        WebSocketRequest webSocketRequest = WebSocketRequest.getRequest(requestTemplate);

        DefaultMessageReply messageReply = webSocketTemplate.replySendMessageToServer(request.getUri(), webSocketRequest.getReplyTo(), session -> {
            try {
                session.getAsyncRemote().sendBinary(ByteBuffer.wrap(HttpInvokerRemoteConstant.objectMapper.writeValueAsBytes(webSocketRequest)));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });

        return messageReply.getResponse(request, httpInvokerProperties.getReadTimeout(), TimeUnit.MILLISECONDS);
    }
}
